# before calling this function use applyStrategy to build blotter accounts

PerformanceSummary <- function (groupcode, latex=FALSE, method="") {
  if('package:xtable' %in% search() || require('xtable',quietly=TRUE)) {}
  if('package:blotter' %in% search() || require('blotter',quietly=TRUE)) {}  
  if('package:PerformanceAnalytics' %in% search() || require('PerformanceAnalytics',quietly=TRUE)) {}
  groupinfo <- getDBGroup(groupcode)
  alist <- ls(envir=.blotter, pattern="^account")
  plist <- ls(envir=.blotter, pattern="^portfolio")

  resDF <- as.data.frame(matrix(0, nrow=length(alist), ncol=13))
  cols <- c("Code", "Trades", "GV", "ARR", "Min", "Mean", "Max", "Sd", "DDev", "Skew", "Kurt", "mDD", "Sortino")
  colnames(resDF) <- cols
  
  # loop through every account
  for (i in 1:length(alist)) {
    symname <- strsplit(strsplit(alist[i], " ")[[1]][2], ".vadb", fixed=TRUE)[[1]][1]

    symname.vadb <- paste(symname, "vadb", sep=".")
    pname <- paste("p", symname.vadb)      

    if (symname == groupcode) {
      notrades <- 0
      for (thissymcode in groupinfo[,"code"]) { #cumulate transactions
        notrades <- notrades + dim(getPortfolio(pname)$symbols[[paste(thissymcode, "vadb", sep=".")]]$txn)[1]-1        
      }
      fromtodates <- c(min(groupinfo[,"from"]), max(groupinfo[,"to"]))
    } else {
      notrades <- dim(getPortfolio(pname)$symbols[[symname.vadb]]$txn)[1]-1  
      fromtodates <- getGroupMember(groupinfo, symname)
    }
    
    subsetstring <- paste(fromtodates[1], fromtodates[2], sep="/")
    End.Eq <- getAccount(alist[i])$summary$End.Eq
    #End.Eq <- End.Eq[subsetstring]
    mRet <- monthlyReturn(End.Eq, type='log', subset=subsetstring)
    # replace all NaN with zeros
    #mRet[is.nan(mRet)] <- 0
    #mRet[is.infinite(mRet)] <- 0
    overallGV <- as.vector(last(End.Eq)) - as.vector(first(End.Eq))
    annualizedRet <- Return.annualized(mRet, scale=12)
    # for daily returns:
    #charts.PerformanceSummary(ROC(getAccount(alist[i])$summary$End.Eq), main=paste("Return / Drawdown Plot for", symname))
    charts.PerformanceSummary(mRet, main=paste("Return / Drawdown Plot for", symname))
    # a table with monthly returns:
    # table.CalendarReturns(mRet)
    # get some stats of the monthly returns
    stats <- table.Stats(mRet)

    # fill resDF with values
    resDF[i,"Code"] <-   symname
    resDF[i,"Trades"] <- notrades
    resDF[i,"GV"] <-     overallGV
    resDF[i,"ARR"] <-    annualizedRet*100
    resDF[i,"Max"] <-    stats["Maximum",]*100
    resDF[i,"Mean"] <-   stats["Arithmetic Mean",]*100
    resDF[i,"Min"] <-    stats["Minimum",]*100
    resDF[i,"Sd"] <-     stats["Stdev",]*100
    resDF[i,"DDev"] <-   DownsideDeviation(mRet, method="full")*100
    resDF[i,"Skew"] <-   stats["Skewness",]
    resDF[i,"Kurt"] <-   stats["Kurtosis",]
    resDF[i,"mDD"] <-    maxDrawdown(mRet)*100
    resDF[i,"Sortino"] <-SortinoRatio(mRet)*100
  }
  resDF <- resDF[with(resDF, order(-GV)), ]
  # add sum line
  sumLine <- as.data.frame(matrix(0, nrow=1, ncol=13))
  colnames(sumLine) <- cols
  sumLine[1,"Code"] <- "SUM"
  sumLine[1,"Trades"] <- sum(resDF[,"Trades"])
  sumLine[1,"GV"] <- sum(resDF[,"GV"])
  sumLine[1,"ARR"] <- mean(resDF[,"ARR"])
  resDF <- rbind(resDF, sumLine)
  
  if (latex==TRUE) {
    title <- sprintf("Anwendung der Kursmuster auf Einzelwerte des Datensatzes %s. %s", groupcode, method)
    label <- sprintf("tab:Simulation:%s.%s", groupcode, method)
    xt <- xtable(resDF,
                 caption=title,
                 label=label,
                 align="r|rr|rr|ccccc|cc|cc|",
                 display=c("s","s","d","d","f","f","f","f","f","f","f","f","f","f"))
    print(xt, include.rownames=FALSE)
  } else {
    return (resDF)
  }
}

PSHistogramOfReturns <- function(groupcode, symname, period="monthly") {
  if('package:blotter' %in% search() || require('blotter',quietly=TRUE)) {}  
  if('package:PerformanceAnalytics' %in% search() || require('PerformanceAnalytics',quietly=TRUE)) {}
  groupinfo <- getDBGroup(groupcode)
  alist <- ls(envir=.blotter, pattern="^account")
  plist <- ls(envir=.blotter, pattern="^portfolio")
  symname.vadb <- paste(symname, "vadb", sep=".")
  pname <- paste("p", symname.vadb)
  aname <- paste("a", symname.vadb)
  
  End.Eq <- getAccount(aname)$summary$End.Eq
  #End.Eq <- End.Eq[subsetstring]
  if (period == "monthly") {
    Ret <- monthlyReturn(End.Eq, type='log', subset=subsetstring)
  } else if (period == "daily") {
    Ret <- dailyReturn(End.Eq, type='log', subset=subsetstring)    
  }
  chart.Histogram(Ret*100, main=paste("Monatliche Renditen von",symname), breaks=30,
                  methods=c("add.density", "add.normal", "add.rug"))
  return (Ret)
}
